﻿using System;
using System.Collections.Generic;
using System.Linq;
using SellAndBuy.Domain.Core;

namespace SellAndBuy.Domain.Entities
{
    /// <summary>
    /// Base class for pictured objects (item, Ad, ...)
    /// </summary>
    public abstract class PicturableBase : EntityBase<PicturableBase, int>, IPicturable
    {
        protected readonly IList<PictureInfo> _pictures = new List<PictureInfo>();

        /// <summary>
        /// Pictures
        /// </summary>
        public virtual IEnumerable<PictureInfo> Pictures
        {
            get
            {
                return _pictures;
            }
        }

        /// <summary>
        /// Main Picture
        /// </summary>
        public virtual PictureInfo MainPicture
        {
            get { return Pictures.FirstOrDefault(p => p.IsMain); }
        }

        /// <summary>
        /// Add Picture to item
        /// </summary>
        /// <param name="picture">Picture contents</param>
        /// <param name="fileName">File name</param>
        /// <param name="title">Name</param>
        /// <exception cref="InvalidOperationException">Picture with the same file name already exists in this item</exception>
        public virtual void AddPicture(byte[] picture, string fileName, string title)
        {
            if (_pictures.FirstOrDefault(pic => pic.FileName == fileName) != null)
                throw new InvalidOperationException("Picture with the same file name already exists in this item");

            // If first picture then make it main picture
            var isMain = _pictures.Count == 0;

            _pictures.Add(new PictureInfo(fileName, title, picture, isMain));
        }

        /// <summary>
        /// Remove picture
        /// </summary>
        /// <param name="picture"></param>
        public virtual void RemovePicture(PictureInfo picture)
        {
            _pictures.Remove(picture);
        }

        /// <summary>
        /// Set main picture
        /// </summary>
        /// <param name="picture"></param>
        public virtual void SetMainPicture(PictureInfo picture)
        {
            if (MainPicture != null)
                MainPicture.IsMain = false;

            _pictures.Single(pic => pic.FileName == picture.FileName).IsMain = true;
        }

    }
}
